package com.job.client.company.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.job.client.common.result.AppHttpCode;
import com.job.client.common.result.ResponseResult;
import com.job.client.company.mapper.AuthenticationMapper;
import com.job.client.company.mapper.CompanyMapper;
import com.job.client.company.service.AuthenticationService;
import com.job.client.model.company.pojo.Authentication;
import com.job.client.model.company.pojo.Company;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AuthenticationServiceImpl extends ServiceImpl<AuthenticationMapper, Authentication>
        implements AuthenticationService {
    @Autowired
    private AuthenticationMapper authenticationMapper;
    @Autowired
    private CompanyMapper companyMapper;

    @Override
    public ResponseResult userIsAuth(String userId) {
        if(userId==null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        if(userId.charAt(0) == '"'){
            userId =  userId.substring(1);
        }
        if(userId.charAt(userId.length()-1) == '"'){
            userId = userId.substring(0,userId.length()-1);
        }
        QueryWrapper<Authentication> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        Authentication authentication = authenticationMapper.selectOne(queryWrapper);
        if(authentication==null){
            return ResponseResult.ErrorResult(AppHttpCode.COMPANY_AUTHENTICATION_FAIL);
        }
        Company company = companyMapper.selectById(authentication.getCompanyId());
        return ResponseResult.OkResult(company);
    }

    @Override
    @Async  //异步操作服务
    public ResponseResult saveUser(String userId, String companyId) {
        Authentication authentication=new Authentication(companyId,userId);
        int i = authenticationMapper.insert(authentication);
        if(i==1){
            return ResponseResult.OkResult();
        }
        return ResponseResult.ErrorResult(AppHttpCode.SERVICE_ERROR);
    }

    @Override
    public ResponseResult authNumber(String companyId) {
        if(companyId == null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        QueryWrapper<Authentication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id",companyId);
        Long count = authenticationMapper.selectCount(queryWrapper);
        return ResponseResult.OkResult(count);
    }

    public Long getAuthCount(String companyId){
        QueryWrapper<Authentication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id",companyId);
        Long count = authenticationMapper.selectCount(queryWrapper);
        return count;
    }

}
